import json
import requests
import config.globalVariable as gv
import random
import re
import time

def __gettimestamp()->int:
    '''获取时间戳'''
    return int(time.time() * 1000)+1
def __getParamCb()->str:
    '''获取参数cb'''
    m = "1.12.3"
    Eb = __gettimestamp()
    return 'jQuery' +re.sub(r'\D', '', m + str(random.random()))+ "_" + str(Eb)

def getShangShenZhenVol():
    '''获取上证 深证成交量'''
    cb = __getParamCb()
    time = str(__gettimestamp())
    url = gv.dfcfApiAddress +'/qt/ulist/get?fltt=1&invt=2&cb='+cb+'&fields=f12%2Cf13%2Cf14%2Cf1%2Cf2%2Cf4%2Cf3%2Cf152%2Cf6%2Cf104%2Cf105%2Cf106&secids=1.000001%2C0.399001&ut=fa5fd1943c7b386f172d6893dbfba10b&pn=1&np=1&pz=20&wbp2u=%7C0%7C1%7C0%7Cweb&_='+time
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Safari/605.1.15'
    }
    # 去除证书警告
    requests.packages.urllib3.disable_warnings()
    # 发送POST请求
    response = requests.get(url, headers=headers, verify=False)
    # 将编码设置为当前编码
    response.encoding = response.apparent_encoding
    if response.status_code != 200 or response.text is None or response.text.find(cb)==-1:
        return None
    # 解析JSON数据
    reqRes = response.text
    reqRes = reqRes[reqRes.find(cb)+len(cb)+1:len(reqRes)-2]
    reqResJson = json.loads(reqRes)
    data = reqResJson.get('data')
    diff = data.get('diff')
    return diff

def getBeiXiangMoney():
    '''获取北向金额'''
    cb = __getParamCb()
    time = str(__gettimestamp())
    url = gv.dfcfApiAddress +'/qt/kamt/get?fields1=f1,f2,f3,f4&fields2=f51,f52,f53,f54,f63&ut=fa5fd1943c7b386f172d6893dbfba10b&cb='+cb+'&_='+time
    headers = {
        'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.0 Safari/605.1.15'
    }
    # 去除证书警告
    requests.packages.urllib3.disable_warnings()
    # 发送POST请求
    response = requests.get(url, headers=headers, verify=False)
    # 将编码设置为当前编码
    response.encoding = response.apparent_encoding
    if response.status_code != 200 or response.text is None or response.text.find(cb)==-1:
        return None
    # 解析JSON数据
    reqRes = response.text
    reqRes = reqRes[reqRes.find(cb)+len(cb)+1:len(reqRes)-2]
    reqResJson = json.loads(reqRes)
    data = reqResJson.get('data')
    return data


if __name__ == '__main__':
    res =getShangShenZhenVol()
    print(res)
    res = getBeiXiangMoney()
    print(res)